package com.king.oa.service.impl;

import java.util.List;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.king.oa.base.DaoSupportImpl;
import com.king.oa.domain.Forum;
import com.king.oa.domain.PageBean;
import com.king.oa.domain.Reply;
import com.king.oa.domain.Topic;
import com.king.oa.service.ReplyService;

@Service
@Transactional
@SuppressWarnings("unchecked")
public class ReplyServiceImpl extends DaoSupportImpl<Reply> implements ReplyService {

	@Override
	public List<Reply> findByTopic(Topic topic) {
		return getSession().createQuery(//
				"FROM Reply r WHERE r.topic=? ORDER BY r.postTime ASC")//
				.setParameter(0, topic)//
				.list();
	}
	
	@Override
	public void save(Reply reply) {
		//保存
		getSession().save(reply);
		
		//维护相关的信息
		Topic topic = reply.getTopic();
		Forum forum = topic.getForum();
		
		forum.setArticleCount(forum.getArticleCount() + 1);	// 文章数量 （主题数+回复数）
		
		topic.setReplyCount(topic.getReplyCount() + 1); 	// 回复数量
		topic.setLastReply(reply);          				// 最后发表的回复
		topic.setLastUpdateTime(reply.getPostTime());		// 最后更新的时间（主题发表时或最后回复的时间）
		
		getSession().update(topic);
		getSession().update(forum);
		
	}

	@Override
	public PageBean findPageBeanByTopic(int pageNum, int pageSize, Topic topic) {
		
		//查询本页的数据列表
		List<Topic> recordList = getSession().createQuery(//
				"FROM Reply r WHERE r.topic=? ORDER BY r.postTime ASC")//
				.setParameter(0, topic)//
				.setFirstResult((pageNum - 1) * pageSize)//
				.setMaxResults(pageSize)//
				.list();
		
		//查询总记录数量
		Long recordCount = (Long) getSession().createQuery(//
				"SELECT COUNT(*) FROM Reply r WHERE r.topic=?")//
				.setParameter(0, topic)//
				.uniqueResult();
		
		return new PageBean(pageNum, pageSize, recordCount.intValue(), recordList);
	}


}
